package com.cicc.beergamevirtualsimulationsystem.utils;

import cn.hutool.json.JSONUtil;
import com.cicc.beergamevirtualsimulationsystem.common.errorEnum.RegisterErrorEnum;
import com.cicc.beergamevirtualsimulationsystem.common.exception.BizException;
import com.cicc.beergamevirtualsimulationsystem.model.R;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * @author 银角大王
 */
public class HttpUtil {

    private static final String SMS_URL = "https://srm.ci2c.com.cn/api/admin/beer-game";

    /**
     * 发送验证码消息
     * @param phone
     */
    public static void sendMsg(String phone) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(SMS_URL +"/"+phone)
                .build();
        try (Response response = client.newCall(request).execute()) {
            R res = JSONUtil.toBean(response.body().string(), R.class);

            if(res.getCode() != 0){
                throw new BizException(RegisterErrorEnum.SENT_SMS_FAIL_ERROR.getCode(), RegisterErrorEnum.SENT_SMS_FAIL_ERROR.getDesc());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 校验验证码
     * @param phone
     * @param captcha
     */
    public static Boolean checkCode(String phone,String captcha){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(SMS_URL+ "/check?mobile="+phone +"&captcha="+captcha)
                .build();
        try (Response response = client.newCall(request).execute()) {
            R res = JSONUtil.toBean(response.body().string(), R.class);
            return res.getCode() != 1;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
